from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException

def main(client, customer_id, location_ids, language_id, keyword_texts=None, page_url=None):
    keyword_plan_idea_service = client.get_service("KeywordPlanIdeaService")

    # 获取地区和语言资源名称
    location_rns = [client.get_service("GeoTargetConstantService").geo_target_constant_path(location_id) for location_id
                    in location_ids]
    language_rn = client.get_service("GoogleAdsService").language_constant_path(language_id)

    # 检查输入参数
    if not (keyword_texts or page_url):
        raise ValueError("At least one of keywords or page URL is required, but neither was specified.")

    # 构建请求体
    request = client.get_type("GenerateKeywordIdeasRequest")
    request.customer_id = customer_id
    request.language = language_rn
    request.geo_target_constants.extend(location_rns)
    request.include_adult_keywords = False
    request.keyword_plan_network = client.enums.KeywordPlanNetworkEnum.GOOGLE_SEARCH_AND_PARTNERS

    # 根据输入条件构建请求
    if page_url:
        request.url_seed.url = page_url
    if keyword_texts:
        request.keyword_seed.keywords.extend(keyword_texts)

    # 发送请求并处理响应
    try:
        keyword_ideas = keyword_plan_idea_service.generate_keyword_ideas(request)
        for idea in keyword_ideas:
            competition_value = idea.keyword_idea_metrics.competition.name
            print(
                f'Keyword idea text "{idea.text}" has '
                f'"{idea.keyword_idea_metrics.avg_monthly_searches}" '
                f'average monthly searches and "{competition_value}" competition.\n'
            )
    except GoogleAdsException as ex:
        # 改善异常处理
        print(f"Request failed with status {ex.error.code().name}: {str(ex)}")


if __name__ == "__main__":
    # 加载Google Ads API客户端
    client = GoogleAdsClient.load_from_storage("google-ads.yaml")

    # 获取OAuth2的开发者令牌、客户ID等信息
    customer_id = "8481425237"
    language_id = "1000"  # 英文
    location_ids = ["2840"]  # 美国
    keyword_texts = ["btc", "eth", "sol"]  # 关键字列表
    page_url = None  # 或者设置为某个页面 URL

    main(client, customer_id, location_ids, language_id, keyword_texts, page_url)










# from google.ads.googleads.client import GoogleAdsClient
# from google.ads.googleads.errors import GoogleAdsException
# import logging
#
# # 设置日志记录
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)
#
# def main(client, customer_id):
#     query = """
#     SELECT
#       customer.id
#     FROM
#       customer
#     LIMIT 1
#     """
#
#     logger.info(f"正在使用客户 ID: {customer_id}")
#     logger.info("执行查询: %s", query)
#
#     google_ads_service = client.get_service("GoogleAdsService")
#
#     try:
#         logger.info("发送请求到 Google Ads API...")
#         response = google_ads_service.search(customer_id=customer_id, query=query)
#
#         for row in response:
#             logger.info(f"客户 ID: {row.customer.id.value}")
#
#     except GoogleAdsException as ex:
#         logger.error("请求失败，状态：%s，消息：'%s'。", ex.error.code().name, ex.error.message)
#     except Exception as ex:
#         # 捕获 _InactiveRpcError
#         if hasattr(ex, 'details'):
#             logger.error("发生了意外错误：%s", ex.details)
#         else:
#             logger.error("发生了意外错误：%s", str(ex))
#
#     finally:
#         logger.info("请求处理结束。")
#
# if __name__ == "__main__":
#     client = GoogleAdsClient.load_from_storage("google-ads.yaml")
#     logger.info("Google Ads Client Loaded Successfully!")
#     main(client, "8481425237")  # 用你的客户 ID 替换














# from google.ads.googleads.client import GoogleAdsClient
# from google.ads.googleads.errors import GoogleAdsException
#
# def main(client, customer_id):
#     query = """
#     SELECT
#       customer.id
#     FROM
#       customer
#     LIMIT 1
#     """
#
#     google_ads_service = client.get_service("GoogleAdsService")
#
#     try:
#         response = google_ads_service.search(customer_id=customer_id, query=query)
#
#         for row in response:
#             print(f"客户 ID: {row.customer.id.value}")
#
#     except GoogleAdsException as ex:
#         print(f"请求失败，状态：{ex.error.code().name}，消息：'{ex.message}'。")
#     except Exception as ex:
#         print(f"发生了意外错误：{str(ex)}")
#
# if __name__ == "__main__":
#     client = GoogleAdsClient.load_from_storage("google-ads.yaml")
#     main(client, "8481425237")  # 用你的客户 ID 替换















# def main(client, customer_id):
#     ga_service = client.get_service("GoogleAdsService")
#     query = "SELECT campaign.id, campaign.name FROM campaign"
#
#     # 使用 search_stream
#     stream = ga_service.search_stream(customer_id=customer_id, query=query)
#     for batch in stream:
#         for row in batch.results:
#             print(f"Campaign ID: {row.campaign.id.value}, Name: {row.campaign.name.value}")
#
# if __name__ == "__main__":
#     client = GoogleAdsClient.load_from_storage("google-ads.yaml")
#     customer_id = "8481425237"  # 替换为你的客户ID
#     main(client, customer_id)













# def main(client, customer_id, location_ids, language_id, keyword_texts=None, page_url=None):
#     keyword_plan_idea_service = client.get_service("KeywordPlanIdeaService")
#
#     # 获取地区和语言资源名称
#     location_rns = [client.get_service("GeoTargetConstantService").geo_target_constant_path(location_id) for location_id
#                     in location_ids]
#     language_rn = client.get_service("GoogleAdsService").language_constant_path(language_id)
#
#     # 检查输入参数
#     if not (keyword_texts or page_url):
#         raise ValueError("At least one of keywords or page URL is required, but neither was specified.")
#
#     # 构建请求体
#     request = client.get_type("GenerateKeywordIdeasRequest")
#     request.customer_id = customer_id
#     request.language = language_rn
#     request.geo_target_constants.extend(location_rns)
#     request.include_adult_keywords = False
#     request.keyword_plan_network = client.enums.KeywordPlanNetworkEnum.GOOGLE_SEARCH_AND_PARTNERS
#
#     # 根据输入条件构建请求
#     if page_url:
#         request.url_seed.url = page_url
#     if keyword_texts:
#         request.keyword_seed.keywords.extend(keyword_texts)
#
#     # 发送请求并处理响应
#     try:
#         keyword_ideas = keyword_plan_idea_service.generate_keyword_ideas(request)
#         for idea in keyword_ideas:
#             competition_value = idea.keyword_idea_metrics.competition.name
#             print(
#                 f'Keyword idea text "{idea.text}" has '
#                 f'"{idea.keyword_idea_metrics.avg_monthly_searches}" '
#                 f'average monthly searches and "{competition_value}" competition.\n'
#             )
#     except GoogleAdsException as ex:
#         print(f"Request failed with status {ex.error.code()}: {ex.error.message}")
#
#
# if __name__ == "__main__":
#     # 加载Google Ads API客户端
#     client = GoogleAdsClient.load_from_storage("google-ads.yaml")
#
#     # 获取OAuth2的开发者令牌、客户ID等信息
#     customer_id = "8481425237"
#     language_id = "1000"  # 英文
#     location_ids = ["2840"]  # 美国
#     keyword_texts = ["btc", "eth", "sol"]  # 关键字列表
#     page_url = None  # 或者设置为某个页面 URL
#
#     main(client, customer_id, location_ids, language_id, keyword_texts, page_url)
